// pages/fabu/form/form.js
var api = require('../../utils/util.js').default;
var app = getApp();
Page({
  data: {
    serviceName: '', //界面显示的服务类型
    meet_place: "", //交接地点
    unit_price: 1, //单价

    cus_details: "", //客户的备注信息
    is_matched: 0, //是否匹配到骑手
    upload_time: "", //订单提交时间
    torider: "", //骑手名
    tocustomer: "", //客户名
    on_working: 0, //订单是否被配送
    is_outdata: 0, //订单是否完成
    is_failed: 0, //订单是否被遗弃
    shoppingId: "1",
    submitTime: "", //返回用户提交订单的时间作为时间凭据
    select_rider: "指定骑手",
    time: 1, //失效时间

    confirmBoxVisible:false,
    choose_rider: false, //选择骑手
    rider: "0", // 骑手openid
    show_rider: "可忽略，等待快速匹配",

    serve: false,
    serve_type: null,
    show_servertype: "选择订单类型",
    serve_list: ['代拿快递', '代拿外卖', '食堂代拿', '超市代买'],



    img_num: 0,
    imgList: null, // 图片本地地址

  },

  onLoad: function () {
    wx.setStorageSync('select_rider', "0");
  },

  // 图片选择接口
  ChooseImage() {
    wx.chooseImage({
      count: 1, //默认9
      sizeType: ['compressed'], //可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], //从相册选择
      success: (res) => {
        console.log(res)
        this.setData({
          imgList: res.tempFilePaths[0],
          img_num: 1
        })
      }
    });
  },
  // 图片预览接口
  ViewImage(e) {
    wx.previewImage({
      urls: this.data.imgList,
      current: e.currentTarget.dataset.url
    });
  },
  // 图片删除接口
  DelImg(e) {
    this.setData({
      imgList: this.data.imgList,
      img_num: 0,
    })
  },

  // 获取服务类型
  getServeType: function (e) {
    if (e.detail.value) {
      var serve_num = parseInt(e.detail.value) + 1
      var show_servertype = this.data.serve_list[serve_num - 1];
      console.log(show_servertype)
      this.setData({
        serve: true,
        serve_num: serve_num,
        show_servertype: show_servertype
      })
    }
  },

  // 选择骑手页面
  chooseRider: function () {
    wx.navigateTo({
      url: '../square_cuspush_chooseRider/square_cuspush_chooseRider',
    })
  },

  // 检测骑手是否选择
  checkRider: function () {
    var rider = wx.getStorageSync('select_rider')
    if (rider.length > 5) {
      this.setData({
        choose_rider: true,
        rider: rider,
        show_rider: "已选择固定骑手"
      })
    } else {
      this.setData({
        choose_rider: false,
        rider: "0",
        show_rider: "可忽略，等待快速匹配",
      })
    }
  },

  // 获取订单单价
  getUnitPrice: function (e) {
    let unit_price = parseInt(e.detail.value);
    if (unit_price < 1 || !unit_price) {
      this.setData({
        unit_price: 1
      });
    } else this.setData({
      unit_price
    });
    console.log(this.data.unit_price)
  },

  // 获取失效时间
  getTime: function (e) {
    let time = parseInt(e.detail.value);
    if (time < 1 || !time) {
      this.setData({
        time: 1
      });
    } else this.setData({
      time
    });
    console.log("订单时间" + this.data.time);
  },

  // PC端数字输入修复 
  fixNumber: function (e) {
    var value = this.validateNumber(e.detail.value);
    return value;
  },
  validateNumber(val) {
    return val.replace(/\D/g, '');
  },

  // 提示关于失效时间
  aboutTime: function () {
    wx.showModal({
      title: '提示',
      content: '失效时间：订单提交成功后，若超过失效时间则订单将会被取消，可申请退款。失效时间最短为1小时（单位：小时）',
      showCancel: false,
      confirmText: '确定',
      confirmColor: '#3CC51F',
    });
  },

  // 提示关于单价
  aboutUnitPrice: function () {
    wx.showModal({
      title: '提示',
      content: '最低金额不低于1元',
      showCancel: false,
      confirmText: '确定',
      confirmColor: '#3CC51F',
    });
  },

  // 获取交接地点
  getPlace: function (e) {
    let meet_place = e.detail.value;
    this.setData({
      meet_place
    });
  },

  // 获取备注信息
  getDetails: function (e) {
    let cus_details = e.detail.value;
    this.setData({
      cus_details
    });
  },

  // 订单确认弹窗
  confirm: function () {
    this.setData({
      confirmBoxVisible: true,
    })
    let time = api.formatTime(new Date());
    this.setData({
      submitTime: time
    });
  },

  close: function () {
    this.setData({
      confirmBoxVisible: false,
    })
  },


  // 订单提交接口
  submit: function (e) {
    var that = this;
    if (!that.data.serve || that.data.meet_place === "" || that.data.unit_price === "" || !that.data.time) {
      if (!that.data.serve) {
        wx.showToast({
          title: '请选择服务类型',
          icon: 'loading',
          duration: 1000
        })
      } else if (that.data.meet_place === "") {
        wx.showToast({
          title: '请填写交接地点',
          icon: 'loading',
          duration: 1000
        })
      } else if (that.data.unit_price === "") {
        wx.showToast({
          title: '请填写订单金额',
          icon: 'loading',
          duration: 1000
        })
      } else if (!that.data.time) {
        wx.showToast({
          title: '请填写失效时间',
          icon: 'loading',
          duration: 1000
        })
      } else {
        wx.showToast({
          title: '请检查表单',
          icon: 'loading',
          duration: 1000
        })
      }
    } else {
      this.close();
      let time = api.formatTime(new Date());
      this.setData({
        submitTime: time
      });
      var data = {
        openid: app.globalData.openid,
        fee: this.data.unit_price,
      }
      api.pay(data).then(result => {
        console.log('1.预支付信息：')
        console.log(result.data)
        var otn = result.data.out_trade_no
        wx.requestPayment({
          nonceStr: result.data['nonceStr'],
          package: result.data['package'],
          signType: 'MD5',
          paySign: result.data['paySign'],
          timeStamp: result.data['timeStamp'],
          success: function (res) {
            console.log('2.微信支付api接口')
            console.log(res)
            var formData = {
              order_num: otn, //订单号
              sever_type: that.data.serve_num, //服务类型
              meet_place: that.data.meet_place, //交接地点
              unit_price: that.data.unit_price, //单价
              cus_details: that.data.cus_details, //客户的备注信息
              upload_time: that.data.submitTime, //订单提交时间
              torider: that.data.choose_rider ? that.data.rider : '0', //骑手名x
              tocustomer: app.globalData.openid, //客户名
              time_num: that.data.time, // 失效时间
              submitTime: that.data.submitTime, //返回用户提交订单的时间作为时间凭据
            }
            console.log("post订单数据：")
            console.log(formData);

            if (that.data.img_num == 1) {
              api.newOrder_file(that.data.imgList, formData).then(result => {
                console.log('3.传订单接口(图片模式)')
                console.log(result.data)
                if (result.data == 1) {
                  wx.showToast({
                    title: '提交成功',
                    icon: 'success',
                    duration: 1000,
                    mask: false,
                  });
                  setTimeout(function () {
                    wx.switchTab({
                      url: '../square/square'
                    })
                  }, 1500)
                } else {
                  wx.showToast({
                    title: '发生错误，请联系客服',
                  })
                }
                wx.setStorageSync('select_rider', "无");
              })
            } else {
              api.newOrder(formData).then(result => {
                console.log('3.传订单接口(无图模式)')
                console.log(result.data)
                if (result.data == "参数错误") {
                  wx.showToast({
                    title: '发生错误，请联系客服',
                  })
                } else {
                  setTimeout(function () {
                    wx.switchTab({
                      url: '../square/square'
                    })
                  }, 1500)
                }
              })
              wx.setStorageSync('select_rider', "0");
            }
            wx.showToast({
              title: '支付成功',
              icon: 'success',
              duration: 1500
            })
          }
        })
      })
    }
  },

})